#encoding: UTF-8
from flask import Flask,render_template,request,redirect,session,url_for,g
import config
from sqlalchemy import or_

from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop

from exts import db
from models import User,Post,Comment

app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)


@app.route('/')
def index():
	context = {
		'posts': Post.query.order_by('-time').all()
	}
	return render_template('index.html', **context)


@app.route('/login', methods = ['GET', 'POST'])
def login():
	if request.method == 'GET':
		return render_template('login.html')
	else:
		username = request.form.get('username')
		password = request.form.get('password')
		user = User.query.filter(User.username == username).first()
		if user:
			if user.check_password(password):
				session['userid'] = user.id
				session.permanent = True
				return redirect('/')
			else:
				return render_template('message.html', message = '密码错误！请重试。')
		else:
			return render_template('message.html', message = '该用户不存在！')


@app.route('/regist', methods = ['GET', 'POST'])
def regist():
	if request.method == 'GET':
		return render_template('regist.html')
	else:
		username = request.form.get('username')
		password = request.form.get('password')
		password_repeat = request.form.get('password-repeat')

		#用户名或密码为空吗？
		if username == '' or password == '':
			return render_template('message.html', message = '用户名或密码不能为空！')

		#用户名已经存在吗？
		user = User.query.filter(User.username == username).first()
		if user:
			return render_template('message.html', message = '该用户名已经存在！请更换用户名！')

		#两次密码一致吗？
		if password != password_repeat:
			return render_template('message.html', message = '两次输入密码不一致！请核对后再试！')

		user = User(username = username,password = password)
		db.session.add(user)
		db.session.commit()
		return redirect('/login')


@app.route('/logout')
def logout():
	session.clear()
	return redirect('/')


@app.route('/post', methods = ['GET','POST'])
def post():
	if hasattr(g,'user'):
		pass
	else:
		return redirect('/login')
	if request.method == 'GET':
		return render_template('post.html')
	else:
		title = request.form.get('title')
		content = request.form.get('content')
		if title == '' or content == '':
			return render_template('message.html',message='帖子标题或内容不能为空！')
		post = Post(title = title, content = content)
		post.author = g.user
		db.session.add(post)
		db.session.commit()
		return redirect('/')


@app.route('/detail/<id>', methods = ['GET','POST'])
def detail(id):
	post = Post.query.filter(Post.id == id).first()
	if request.method == 'GET':
		return render_template('detail.html', post = post)
	else:
		if hasattr(g,'user'):
			pass
		else:
			return redirect('/login')
		content = request.form.get('content')
		if content == '':
			return render_template('message.html',message='评论不能为空！')
		comment = Comment(content = content)
		post = Post.query.filter(Post.id == id).first()
		comment.author = g.user
		comment.post = post
		db.session.add(comment)
		db.session.commit()
		return redirect(url_for('detail',id = id))


@app.route('/search/')
def search():
	key = request.args.get('key')
	posts = Post.query.filter(or_(Post.title.contains(key),Post.content.contains(key))).order_by('-time')
	if posts.first():
		return render_template('search.html',posts=posts)
	else:
		return render_template('message.html',message='未找到相关帖子！')


@app.before_request
def find_user():
	userid = session.get('userid')
	if userid:
		user = User.query.filter(User.id == userid).first()
		if user:
			g.user = user



@app.context_processor
def is_login():
	if hasattr(g,'user'):
		return {'user':g.user}
	return {}


if __name__=='__main__':
	# app.run(host = '0.0.0.0')
	http_server = HTTPServer(WSGIContainer(app))
	http_server.listen(5000)
	IOLoop.instance().start()